import base64
import os
from django.db import models
import uuid
import hashlib
import time
from datetime import datetime, timedelta

from apps.generate_secret.models import AppSecret


class RootKey(models.Model):
    """
    根密钥表
    用于存储生成的根密钥信息
    """
    KEY_TYPE_CHOICES = [
        ('SM1', 'SM1'),
        ('SM4', 'SM4'),
    ]
    
    STATUS_CHOICES = [
        ('active', '激活'),
        ('inactive', '未激活'),
    ]
    
    id = models.AutoField(primary_key=True, verbose_name="主键ID")
    app_id = models.ForeignKey(
        AppSecret,
        to_field='app_id',  # 指定关联字段
        on_delete=models.SET_NULL,
        null=True,                  # 必须设置 null=True
        blank=True, 
        db_column='app_id'  # 数据库中的列名（可选）
    )

    key_id = models.CharField(max_length=64, unique=True, verbose_name="根密钥ID", help_text="根密钥唯一标识", db_index=True)
    key = models.TextField(verbose_name="根密钥", help_text="根密钥内容")
    key_type = models.CharField(max_length=10, choices=KEY_TYPE_CHOICES, verbose_name="加密算法", help_text="加密算法类型", db_index=True)
    key_length = models.IntegerField(verbose_name="密钥长度", help_text="密钥长度")
    description = models.CharField(max_length=512, verbose_name="密钥描述", null=True, blank=True)
    version = models.CharField(max_length=32, verbose_name="版本号", help_text="密钥版本号")
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='active', verbose_name="状态", help_text="密钥状态", db_index=True)
    created_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True, db_index=True)
    updated_at = models.DateTimeField(verbose_name='更新时间', auto_now=True)
    expired_at = models.DateTimeField(verbose_name='过期时间', null=True, blank=True, help_text="密钥过期时间(作废)")
    create_by = models.CharField(max_length=128, verbose_name='创建者', null=True, blank=True)
    update_by = models.CharField(max_length=128, verbose_name='更新者', null=True, blank=True)
    is_delete = models.BooleanField(default=False, verbose_name="是否删除", help_text="是否逻辑删除", db_index=True)

    class Meta:
        db_table = 'root_key'
        verbose_name = '根密钥表'
        verbose_name_plural = '根密钥表'

    def __str__(self):
        return f"{self.key_id}({self.key_type})"

    @classmethod
    def generate_key_id(cls):
        """生成根密钥ID"""
        timestamp = str(int(time.time()))
        random_uuid = str(uuid.uuid4())
        key_id_string = f"ROOT_{timestamp}_{random_uuid}"
        return hashlib.md5(key_id_string.encode()).hexdigest()[:16]

    @classmethod
    def generate_root_key(cls, key_length=128):
        """生成根密钥（伪函数）"""
        import secrets
        # # 生成指定长度的随机密钥（以字节为单位）
        # key_bytes = secrets.token_bytes(key_length // 8)
        # return key_bytes.hex()
        sm1_key = os.urandom(16)
        base64_str = base64.b64encode(sm1_key).decode('ascii')  # 'jqL...8Q=='

        # hex_key = ' '.join(f"{byte:02X}" for byte in sm1_key)
        return base64_str



    @classmethod
    def generate_version(cls):
        """生成版本号"""
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
        return f"v1.0.{timestamp}"


class KeyAuditLog(models.Model):
    """
    密钥审计日志表
    用于记录密钥操作的审计信息
    """
    OPERATION_CHOICES = [
        ('create', '创建'),
        ('update', '更新'),
        ('delete', '删除'),
        ('activate', '激活'),
        ('deactivate', '停用'),
        ('expire', '过期'),
    ]
    
    id = models.AutoField(primary_key=True, verbose_name="主键ID")
    key_id = models.CharField(max_length=64, verbose_name="根密钥ID", help_text="关联的根密钥ID", db_index=True)
    operation = models.CharField(max_length=20, choices=OPERATION_CHOICES, verbose_name="操作类型", help_text="操作类型", db_index=True)
    operation_time = models.DateTimeField(verbose_name='操作时间', auto_now_add=True, db_index=True)
    operator = models.CharField(max_length=128, verbose_name='操作者', null=True, blank=True)
    ip_address = models.GenericIPAddressField(verbose_name='IP地址', null=True, blank=True)
    user_agent = models.CharField(max_length=512, verbose_name='用户代理', null=True, blank=True)
    details = models.TextField(verbose_name="操作详情", null=True, blank=True, help_text="操作详细信息")
    expired_at = models.DateTimeField(verbose_name='审计记录过期时间', null=True, blank=True, help_text="审计记录过期时间")

    class Meta:
        db_table = 'key_audit_log'
        verbose_name = '密钥审计日志表'
        verbose_name_plural = '密钥审计日志表'

    def __str__(self):
        return f"{self.key_id}_{self.operation}_{self.operation_time.strftime('%Y%m%d%H%M%S')}"
